<?php
class UserDABase extends AbstractDbObject
{
	/**
	 * Table name
	 *
	 * @var string
	 */
	protected $tableName = 'user';

	/**
	 * Table alias
	 *
	 * @var string
	 */
	protected $tableAlias = 'user';

	/**
	 * Create a user
	 *
	 * @access public
	 *
	 * @param UserEntity $userEntity: object
	 *
	 * @return primary key has just been inserted
	 */
	public function create($userEntity)
	{
		try {
			// Get db object
			$dbWriter = $this->getDbWriter();

			// Fetch array
			$data = array(
				'id' => $userEntity->id,
				'email' => $userEntity->email,
				'password' => $userEntity->password,
				'fullname' => $userEntity->fullname,
				'birthday' => $userEntity->birthday,
				'address' => $userEntity->address,
				'phone' => $userEntity->phone,
				'creation_date' => $userEntity->creation_date,
				'last_login' => $userEntity->last_login,
				'balance' => $userEntity->balance,
				'picture' => $userEntity->picture,
				'gender' => $userEntity->gender,
				'status' => $userEntity->status,
                'userType' => $userEntity->userType,
			);

			// Insert into database
			$dbWriter->insert($this->tableName, $data);

			// Return primary key has just created
			return $dbWriter->lastInsertId($this->tableName, 'id');
		} catch(Exception $ex) {			
			
			throw $ex;
		}
	}

	/**
	 * Update a user
	 *
	 * @access public
	 *
	 * @param UserEntity $userEntity: object
	 *
	 * @return bool true if update success otherwise return false
	 */
	public function update($userEntity)
	{
		try {
			// Get db object
			$dbWriter = $this->getDbWriter();

			// Fetch array
			$data = array(
				'email' => $userEntity->email,
				'password' => $userEntity->password,
				'fullname' => $userEntity->fullname,
				'birthday' => $userEntity->birthday,
				'address' => $userEntity->address,
				'phone' => $userEntity->phone,
				'creation_date' => $userEntity->creation_date,
				'last_login' => $userEntity->last_login,
				'balance' => $userEntity->balance,
				'picture' => $userEntity->picture,
				'gender' => $userEntity->gender,
				'status' => $userEntity->status,
                'userType' => $userEntity->userType,
			);

		

			// Update user
			$idQoute = $dbWriter->quote($userEntity->id);
			$where[] = "id = $idQoute";

			// Execute query
			$numRows = $dbWriter->update($this->tableName, $data, $where);
			if($numRows > 0){
				return true;
			}else{
				return false;
			}
		} catch(Exception $ex) {			
			throw $ex;
		}
	}

	/**
	 * Delete a user by Id
	 *
	 * @access public
	 *
	 * @param int $id: Id of user
	 *
	 * @return bool whether delete action is success or not
	 */
	public function del($id)
	{
		try {
			// Get db object
			$dbWriter = $this->getDbWriter();

			// Update user
			$idQuote = $dbWriter->quote($id);

			// Execute query
			$rowCount = $dbWriter->delete($this->tableName, "id = $idQuote");

			// Return boolean result
			if($rowCount > 0){
				return true;
			}else{
				return false;
			}
		} catch(Exception $ex) {
			throw $ex;
		}
	}

	/**
	 * Get UserEntity object by Id of the user
	 *
	 * @access public
	 *
	 * @param int $id: Id of user
	 *
	 * @return UserEntity object
	 */
	public function getById ($id)
	{
		// Get db object
		$dbWriter = $this->getDbWriter();

		// Add quote
		$idQuote = $dbWriter->quote($id);

		// Query for get user by Id
		$query = "
			SELECT {$this->tableName}.*				
			FROM {$this->tableName}  
			WHERE {$this->tableName}.id = $idQuote ";
		$result = $dbWriter->fetchRow($query);
		if (is_null($result) || !is_array($result)){

			// Id of the user does not exist
			return null;
		}
		$userEntity = new UserEntity($result);
		// Return UserEntity object
		return $userEntity;
	}

	/**
	 * Get all rows of user table with search criterias
	 *
	 * @access public
	 *
	 * @param array $arrElement: array of search criterias
	 * @param string $orderBy: Field and the way ordered (ASC or DESC)
	 * @param int $begin: Begin item
	 * @param int $limit: Number rows to query
	 *
	 * @return array of UserEntity object
	 */
	public function getItems($arrElement, $orderBy = null, $begin = null, $limit = null, $where = null)
	{
		// Get db object
		$dbWriter = $this->getDbWriter();

		// Query for get all items of user with search criterias
		$query = "
			SELECT {$this->tableName}.*		
			FROM {$this->tableName} " ;

		$whereTmp = "";
		
		$whereClause = $this->buildWhereClause($arrElement, $dbWriter, $this->tableName);
		$concat = !empty($whereClause) && !empty($whereTmp) ? ' AND ' : '';
		if(empty($whereClause) && !empty($whereTmp)){
			$whereClause = ' WHERE ';
		}
		$query .= " {$whereClause}{$concat}{$whereTmp} ";
		
		if (!empty($where)) {
            $query .= $where;
        }
		$query .= "GROUP BY {$this->tableName}.id ";
		
		// Add order By
		$query .= $this->buildOrderClause($orderBy);

		// Add begin and Limit
		$query .= $this->buildLimitClause($begin, $limit);

		// Execute query
		$result = $dbWriter->fetchAll($query);

		$buffer = null;
		foreach ($result as $element) {
			$userEntity = new UserEntity($element);
			// Add UserEntity into result
			$buffer[] = $userEntity;
		}
		return $buffer;
	}
	public function getItemsAll($arrElement, $orderBy = null, $begin = null, $limit = null, $where = null, $having = null){
		// Get db object
        $dbWriter = $this->getDbWriter();

        // Query for get all items of user deposit with search criterias
        $query = "
			SELECT *
			FROM {$this->tableName}  ";

        // Add where
        $whereTmp = "";
        $whereClause = $this->buildWhereClause($arrElement, $dbWriter,$this->tableName);
        $concat = !empty($whereClause) && !empty($whereTmp) ? ' AND ' : '';
        if (empty($whereClause) && !empty($whereTmp)) {
            $whereClause = ' WHERE ';
        }
        $query .= " {$whereClause}{$concat}{$whereTmp} ";

        if (!empty($where)) {
            $query .= $where;
            
        }

        if (!empty($having)) {
            $query .= " HAVING " . $having;
        }

        // Add order By
        $query .= $this->buildOrderClause($orderBy);

        // Add begin and Limit
        $query .= $this->buildLimitClause($begin, $limit);
        //echo $query;
        // Execute query
        $result = $dbWriter->fetchAll($query);
//
//        $buffer = null;
//        foreach ($result as $element) {
//            $dealsEntity = new DealsEntity($element);
//
//            // Add DealsEntity into result
//            $buffer[] = $dealsEntity;
//        }
        return $result;
	}
	/**
	 * Get total rows of user
	 *
	 * @access public
	 *
	 * @param array $arrElement: array of search criterias
	 *
	 * @return int total: total rows of user
	 */
	public function getTotals($arrElement)
	{
		// Get db object
		$dbWriter = $this->getDbWriter();

		// Query for get total records in user table
		$query = "
			SELECT COUNT(*) as total
			FROM user ";

		$whereTmp  = "";

		// Add where
		$query .= $this->buildWhereClause($arrElement, $dbWriter);
		$query .= $whereTmp;

		// Execute query
		$result = $dbWriter->fetchRow($query);

		if( !is_null($result) ) {
			return (int) $result['total'];
		}

		// Return no record
		return 0;
	}
}